﻿using System;
using System.Windows;
using System.Windows.Media;

namespace MyAnimelistRecommender.Helper
{
    public static class VisualTreeHelperExtender
    {
        public static Visual GetDescendantByType(this Visual element, Type type)
        {
            if (element == null) return null;
            if (element.GetType() == type) return element;
            Visual foundElement = null;
            if (element is FrameworkElement)
            {
                (element as FrameworkElement).ApplyTemplate();
            }
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
            {
                Visual visual = VisualTreeHelper.GetChild(element, i) as Visual;
                foundElement = GetDescendantByType(visual, type);
                if (foundElement != null)
                    break;
            }
            return foundElement;
        }

        public static T GetDescendantByType<T>(this Visual element) where T : Visual, new()
        {
            if (element == null) return default(T);
            if (element.GetType() == typeof(T)) return (T)element;
            Visual foundElement = null;
            if (element is FrameworkElement)
            {
                (element as FrameworkElement).ApplyTemplate();
            }
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
            {
                Visual visual = VisualTreeHelper.GetChild(element, i) as Visual;
                foundElement = visual.GetDescendantByType<T>();
                if (foundElement != null)
                    break;
            }
            return (T)foundElement;
        }
    }
}